<?php
namespace Modules\Admin\Services;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
class WebSocketService implements WebSocketHandlerInterface
{
    public function __construct()
    {
    }
	/**
     * @name 链接开启时
     * @param Server $server
     * @param Request $request
     */
    public function onOpen(Server $server, Request $  )
    {
        $userId = mt_rand(1000, 10000);
		app('swoole')->wsTable->set('uid:' . $userId, ['value' => $request->fd]);
		// 绑定uid到fd的映射
		app('swoole')->wsTable->set('fd:' . $request->fd, ['value' => $userId]);
		// 绑定fd到uid的映射
		$server->push($request->fd, 'Welcome to LaravelS');
    }
	/**
     * @name 接收到消息
     * @param Server $server
     * @param Frame $frame
     */
    public function onMessage(Server $server, Frame $frame)
    {
        foreach (app('swoole')->wsTable as $key => $row) {
			if (strpos($key, 'uid:') === 0 && $server->exist($row['value'])) {
				$server->push($row['value'], $frame->data);
			}
		}
        
    }
	/**
     * @name 关闭服务
     * @param Server $server
     * @param fd $fd
     */
    public function onClose(Server $server, $fd, $reactorId)
    {
       $uid = app('swoole')->wsTable->get('fd:' . $fd);
	   if ($uid !== false) {
			app('swoole')->wsTable->del('uid:' . $uid['value']);// 解绑uid映射
	   }
	   app('swoole')->wsTable->del('fd:' . $fd);//解绑fd映射
	   $server->push($fd, 'Goodbye');
    }
}